package com.imooc.springbootdemo.service.impl;

import com.imooc.springbootdemo.entity.Area;
import com.imooc.springbootdemo.mapper.AreaMapper;
import com.imooc.springbootdemo.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Created by jiangfeixiang on 2018/4/9
 */
@Service
@Transactional
public class AreaServiceImpl implements AreaService {
    //注入AreaMapper
    @Autowired
    private AreaMapper areaMapper;

    /**
     * 查询所有区域
     * @return
     */
    @Override
    public List<Area> queryArea() {
        return areaMapper.getArea();
    }

    /**
     * 根据id查询
     * @param areaId
     * @return
     */
    @Override
    public Area queryAreaById(Integer areaId) {
        return areaMapper.getAreaById(areaId);
    }

    /**
     * 添加区域信息
     * @param area
     * @return
     */
    @Override
    public boolean insertArea(Area area) {
        if(area.getAreaName() !=null && !"".equals(area.getAreaName()) ){
            area.setCreateTime(new Date());
            area.setLastEditTime(new Date());
            try {
                int effectedNum = areaMapper.insertArea(area);
                if (effectedNum>0){
                    return true;
                }else {
                    throw new RuntimeException("插入区域信息失败");
                }
            }catch (Exception e){
                throw new RuntimeException("插入区域信息失败："+e.getMessage());
            }

        }else {
            throw new RuntimeException("区域信息不能为空");
        }
    }

    /**
     * 修改区域信息
     * @param area
     * @return
     */
    @Override
    public boolean updateArea(Area area) {
        if(area.getAreaName() !=null && !"".equals(area.getAreaName()) ){
            area.setLastEditTime(new Date());
            try {
                int effectedNum = areaMapper.updateArea(area);
                if (effectedNum>0){
                    return true;
                }else {
                    throw new RuntimeException("修改区域信息失败");
                }
            }catch (Exception e){
                throw new RuntimeException("修改区域信息失败："+e.getMessage());
            }

        }else {
            throw new RuntimeException("区域信息不能为空");
        }
    }

    /**
     * 根据id删除区域信息
     * @param areaId
     * @return
     */
    @Override
    public boolean deleteArea(int areaId) {
        if(areaId > 0){
            try {
                int effectedNum = areaMapper.deleteArea(areaId);
                if (effectedNum>0){
                    return true;
                }else {
                    throw new RuntimeException("删除区域信息失败");
                }
            }catch (Exception e){
                throw new RuntimeException("删除区域信息失败："+e.getMessage());
            }
        }else {
            throw new RuntimeException("区域信息不能为空");
        }
    }
}
